package com.example.myactspringboot.controller;


import com.example.myactspringboot.bean.BusiTaskMain;
import com.example.myactspringboot.bean.BusiTaskMainVo;
import com.example.myactspringboot.bean.HistoricActivity;
import com.example.myactspringboot.bean.TaskVo;
import com.example.myactspringboot.server.BusiTaskMainService;
import com.example.myactspringboot.util.R;
import com.example.myactspringboot.util.R2;
import com.example.myactspringboot.util.RSAUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.sql.Array;
import java.util.*;

/**
 * @Create 2023-09-16 13:41
 * @Description
 */
@Controller
public class LoginController {
    @Autowired
    private BusiTaskMainService busiTaskMainService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;


    @PostMapping("/doLogin")
    public String doLogin(String encryUsername, String encryPassword, Model model, RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
        String username = RSAUtils.descry(encryUsername);
        String password = RSAUtils.descry(encryPassword);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
//            model.addAttribute("msg","用户名不存在");
            redirectAttributes.addFlashAttribute("msg", "用户名不存在");
            return "redirect:/";
        } catch (IncorrectCredentialsException e) {
            redirectAttributes.addFlashAttribute("msg", "密码错误");
//            model.addAttribute("msg","密码错误");
            return "redirect:/";
        }
//        session.setAttribute("name", username);
//        session.setAttribute("password", password);
//        return "activiti";
        return "redirect:/tomenuPage";
    }

    @GetMapping("/tomenuPage")
    public String tomenuPage() {
        return "menuPage";
    }

    @GetMapping("/toActPage")
    public String toact() {
        return "activiti";
    }

    @GetMapping("/")
    public String tologin(Model model) throws NoSuchAlgorithmException {
        RSAUtils.getKeyPair();
        String publicKey = RSAUtils.keyMap.get("publicKey");
//        System.out.println(publicKey);
        model.addAttribute("publicKey", publicKey);
        return "index";
    }

    @PostMapping("/save")
    @ResponseBody
    public String save(@RequestBody BusiTaskMain busiTaskMain, HttpSession session) {
        String name = (String) session.getAttribute("username");
        if (name == null) {
            return "error";
        }
        busiTaskMain.setId(new Random().nextInt(1000) + 99);
        busiTaskMain.setType("test1");
        busiTaskMain.setCreateBy(name);
        busiTaskMain.setCreateTime(new Date());
        System.out.println(busiTaskMain);
        int i = busiTaskMainService.saveMain(busiTaskMain);
        return i > 0 ? "success" : "error";
    }

    @GetMapping("/getData")
    @ResponseBody
    public R getData(HttpSession session) {
        String name = (String) session.getAttribute("username");
        if (name == null) {
            return R.error();
        }
        BusiTaskMain busiTaskMain = new BusiTaskMain();
        busiTaskMain.setCreateBy(name);
        busiTaskMain.setType("test1");
        List<BusiTaskMainVo> allTaskMain = busiTaskMainService.getAllTaskMain(busiTaskMain);
        return R.ok().data("list", allTaskMain);
    }

    //提交申请
    @PostMapping("/submitTask")
    @ResponseBody
    public R submitTask(@RequestBody BusiTaskMain busiTaskMain, HttpSession session) {
        String name = (String) session.getAttribute("username");
        if (name == null) {
            return R.error();
        }
        //获取main中的审核信息
//        BusiTaskMain busiTaskMain = busiTaskMainMapper.getById(123);
//        System.out.println(busiTaskMain);
        busiTaskMain.setApplyUser(name);  //申请人id
        busiTaskMain.setApplyTime(new Date());
        busiTaskMain.setUpdateBy(name); //更新人id
        String businessKey = busiTaskMain.getId().toString(); // 实体类 ID，作为流程的业务 key
        //流程发起前设置发起人，记录在流程历史中
        identityService.setAuthenticatedUserId(name);
        //指定下一个环节审核人
        HashMap<String, Object> handleMan = new HashMap<>();
        handleMan.put("renshi", busiTaskMain.getTodoManId());
        //流程模型名，业务主表id，下一个审核人
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("test1", businessKey, handleMan);
        String instanceId = processInstance.getId();
        busiTaskMain.setInstanceId(instanceId);
        int i = busiTaskMainService.updateMain(busiTaskMain);
        int todoCount = busiTaskMainService.saveTodoItem(instanceId, busiTaskMain.getTitle(), busiTaskMain.getReason(), busiTaskMain.getType(), busiTaskMain.getTodoManId());
        return todoCount > 0 ? R.ok() : R.error();
    }

    //查看待办任务
    @GetMapping("/todoPage")
    public String todoPage() {
        return "toDoActiviti";
    }

    @GetMapping("/getToDoData")
    @ResponseBody
    public R getToDoList(HttpSession session) {
        String name = (String) session.getAttribute("username");
        if (name == null) {
            return R.error();
        }
        //拾取
//        List<Task> list = taskService.createTaskQuery().taskCandidateUser("1").list();
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(name).list();
        ArrayList<BusiTaskMainVo> busiTaskMainVos = new ArrayList<>();
        for (Task task : tasks) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            BusiTaskMain busiTaskMain = busiTaskMainService.getById(new Integer(processInstance.getBusinessKey()));
            BusiTaskMainVo busiTaskMainVo = new BusiTaskMainVo();
            BeanUtils.copyProperties(busiTaskMain, busiTaskMainVo);
//            System.out.println(task.getName());
            busiTaskMainVo.setTaskName(task.getName());
            busiTaskMainVo.setTaskId(task.getId());
            busiTaskMainVos.add(busiTaskMainVo);
//            System.out.println(busiTaskMain);
        }

        return R.ok().data("list", busiTaskMainVos);
    }

    @GetMapping("/taskMainById/{id}")
    @ResponseBody
    public R taskMainById(@PathVariable String id) {
        BusiTaskMain busiTaskMain = busiTaskMainService.getById(new Integer(id));
        return R.ok().data("data", busiTaskMain);
    }

    //完成待办任务
    @PostMapping("/completetask")
    @ResponseBody
    public R complete(@RequestBody Map map, HttpSession session) {
        String name = (String) session.getAttribute("username");
        if (name == null) {
            return R.error();
        }
        int complete = busiTaskMainService.complete(map, name);
        return complete > 0 ? R.ok() : R.error();
    }

    @GetMapping("/jingliTask")
    public String todojl(@RequestParam String taskId, @RequestParam String id, Model model) {
        model.addAttribute("taskId", taskId);
        model.addAttribute("id", id);
        return "jingliTask";
    }

    @GetMapping("/renshiTask")
    public String torenshiTask(@RequestParam String taskId, @RequestParam String id, Model model) {
        model.addAttribute("taskId", taskId);
        model.addAttribute("id", id);
        return "renshiTask";
    }

    @GetMapping("/getTaskName/{taskId}")
    @ResponseBody
    public String getTaskName(@PathVariable String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String taskDefinitionKey = task.getTaskDefinitionKey();
        return taskDefinitionKey;
    }

    //历史记录
    @GetMapping("/getHisData/{instanceId}")
    @ResponseBody
    public R2 getHisData(@PathVariable String instanceId) {
        List<HistoricActivity> hisData = busiTaskMainService.getHisData(instanceId);
        return R2.ok().data(hisData);
    }

    //跳转到已办页面
    @GetMapping("/toDoneTaskPage")
    public String toDonePage() {
        return "doneTaskPage";
    }

    //已办任务
    @GetMapping("/getDoneTaskData/{page}/{rows}")
    @ResponseBody
    public R2 getDoneData(@PathVariable Integer page, @PathVariable Integer rows) {
        PageHelper.startPage(1, 1);
//        PageHelper.startPage(page, rows);
        List<BusiTaskMainVo> doneData = busiTaskMainService.getDoneData();
        PageInfo<BusiTaskMainVo> busiTaskMainVoPageInfo = new PageInfo<>(doneData, 5);
        return R2.ok().data(busiTaskMainVoPageInfo);
    }

    //撤销
    @PostMapping("/cancelApply/{instanceId}")
    @ResponseBody
    public R2 cancelApply(@PathVariable String instanceId) {
        busiTaskMainService.cancelApply(instanceId, "用户撤销");
        return R2.ok();
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }

}
